import 'package:flutter/material.dart';


typedef RefreshItemWidgetBuilder<T> = Widget Function(BuildContext context, int index,dynamic);


class RefreshListView<T> extends StatefulWidget {
  final List<T> data;
  final RefreshItemWidgetBuilder<T> item;
  final Function(BuildContext context, int index) separatorBuilder;
  final Future<void> Function() onRefresh;
  final Future<void> Function() onLoadMore;
  final Widget loadMoreWidget;

  const RefreshListView(
      {Key key,
      this.data,
      @required this.item,
      @required this.separatorBuilder,
      this.onRefresh,
      this.onLoadMore,
      this.loadMoreWidget})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _refreshListView<T>();
}

class _refreshListView<T> extends State<RefreshListView> {
  ScrollController _controller = ScrollController();
  int loadMore=0;

  @override
  void initState() {
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        if(widget.onLoadMore!=null){
          LoadMore();
        }
      }else{

      }
    });
  }

  void LoadMore() {
    setState(() {
      loadMore=1;
    });
    widget.onLoadMore.call().then((value) =>
        setState(() {
          loadMore=0;
        })
    );

  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        child: ListView.separated(
            controller: _controller,
            itemBuilder: (context, index) {
              Widget w=Container();
              if(loadMore==1&&index==widget.data.length){
                w=CircularProgressIndicator();
              }else{
                w= widget.item(context,index, (widget.data[index] as T));
              }
              return w;
            },
            separatorBuilder: widget.separatorBuilder,
            itemCount: widget.data.length+loadMore),
        onRefresh: widget.onRefresh);
  }
}
